package logic

import (
	"activity/models/cache"
	"activity/models/mysql"
	"activity/pkg"
	"context"
	"fmt"

	"activity/activityRpc/activityRpc"
	"activity/activityRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *activityRpc.LoginRequest) (*activityRpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	user := mysql.User{}
	mysql.DB.Where("tel=?", in.Tel).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("当前用户不存在，请前去注册")
	}

	if pkg.Md5(in.Password) != user.Password {
		return nil, fmt.Errorf("密码错误！")
	}

	sms, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
	if err != nil {
		return nil, err
	}
	if sms != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}

	return &activityRpc.LoginResponse{
		Id: int64(user.ID),
	}, nil
}
